package com.dx.oa.sysmng.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dx.oa.framework.dto.TreeDto;
import com.dx.oa.framework.util.TreeUtil;
import com.dx.oa.framework.util.UserUtils;
import com.dx.oa.sysmng.entity.Dict;
import com.dx.oa.sysmng.entity.Dept;
import com.dx.oa.sysmng.entity.User;
import com.dx.oa.sysmng.service.IDeptService;

/**
 * 部门功能的Controller
 * @author dx911
 *
 */
@Controller
@RequestMapping("/sysmgr/dept")
public class DeptController {
	
	@Autowired
	private IDeptService deptService;

	private static Logger logger = Logger.getLogger(DeptController.class);

	/**
	 * 进入字典查询功能
	 * @return
	 */
	@RequestMapping("/gotoDeptList")
	public String gotoDeptList(Model model)
	{
		
		List<Dept> sortDeptList = new ArrayList<Dept>();
		List<Dept> deptList =  deptService.getDeptListByUserId(UserUtils.getCurrentUserId());
		TreeUtil.sortTreeList(deptList, sortDeptList, 0);
		model.addAttribute("deptList",sortDeptList);
		
		return "sysmanage/dept/deptList";
	}
	
	//进入字典编辑功能
	@RequestMapping("/gotoDeptEdit")
	public String gotoDeptEdit(@ModelAttribute("editFlag") int editFlag, Integer deptId,Integer parentId, Model model)
	{	
		if(editFlag == 2 && deptId != null)
		{
			model.addAttribute("dept", deptService.getDeptById(deptId));
		}
		if(editFlag == 1 && parentId != null)
		{
			Dept dept = new Dept();
			dept.setParentId(parentId);
			dept.setParentName(deptService.getDeptById(parentId).getName());
			model.addAttribute("dept", dept);
		}
		return "sysmanage/dept/deptEdit";
	}
	
	/**
	 * 对于树形结构的数据,我们在删除的时候需要注意,必须保证无子节点删除
	 * @param deptId
	 * @return
	 */

	@RequestMapping("/delDept")
	public @ResponseBody Map<String,Object> delDept(Integer deptId)
	{
		Map<String,Object> resultMap = new HashMap<String,Object>();
		if(deptService.getChildCnt(deptId) > 0)
		{
			resultMap.put("result", "请先删除该菜单下的子菜单");
			return resultMap;
		}
		try
		{
			int row = deptService.deleteDeptById(deptId);
			if(row > 0)
			{
				resultMap.put("result", "删除成功");
			}
			else
			{
				resultMap.put("result", "删除失败");
				logger.error("删除菜单失败");
			}
		}
		catch(Exception e)
		{
			resultMap.put("result", "删除失败");
			logger.error("删除菜单失败",e);
		}
		return resultMap;
	}

	/**
	 * 获取所有树形结构菜单节点信息，
	 * @param deptId
	 * @return
	 */
	@RequestMapping("/getParentDeptTreeData")
	public @ResponseBody List<TreeDto> getParentDeptTreeData(Integer deptId)
	{
		logger.info(deptId);
		//deptId = 30;

		List<TreeDto> resDeptList = new ArrayList<TreeDto>();
	
		List<Dept> deptList = deptService.getDeptList();
		
		for(Dept dept:deptList)
		{
			resDeptList.add(dept);
		}
		
		if(deptId != null)
		{
			Set<Integer> retSet = TreeUtil.getChildHashSet(resDeptList,deptId);
			List<TreeDto> retDeptList = new ArrayList<TreeDto>();
			for(TreeDto td:resDeptList)
			{
				if(!retSet.contains(td.getId()))
				{
					retDeptList.add(td);
				}
			}
			return retDeptList;
		}

		return resDeptList;
	}
	
	//保存修改
	@RequestMapping("/saveDept")
	public @ResponseBody Map<String,String> saveDept(Dept dept,HttpSession session,Model model)
	{
		System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + ":");
		System.out.println(dept);
		Map<String,String> responseMap = new HashMap<String,String>();
		
		//System.out.println("mdict:"+ mdict.toString());
		
		if(dept == null)
		{
			responseMap.put("result", "操作失败");
			return responseMap;
		}
		dept.setDelFlag('0');
		dept.setUpdateBy(((User)session.getAttribute("user")).getUserNo());
		dept.setUpdateDate(new Timestamp(System.currentTimeMillis()));
		
		if(dept.getId() == null)
		{
			if(deptService.insertDept(dept) > 0)
			{
				List<Dept> deptList =  deptService.getDeptList();
				List<Dept> sortDeptList = new ArrayList<Dept>();
				TreeUtil.sortTreeList(deptList, sortDeptList, 0);
				model.addAttribute("deptList", sortDeptList);
				responseMap.put("result", "插入成功");
			}
			else
				responseMap.put("result", "插入失败");
		}
		else
		{
			if(deptService.updateDept(dept) > 0)
			{
				List<Dept> deptList =  deptService.getDeptList();
				List<Dept> sortDeptList = new ArrayList<Dept>();
				TreeUtil.sortTreeList(deptList, sortDeptList, 0);
				model.addAttribute("deptList", sortDeptList);
				responseMap.put("result","更新成功");
			}
			else
				responseMap.put("result", "更新失败");
		}
		return responseMap;
	}
	
	@RequestMapping("/getAllDeptList")
	public @ResponseBody List<Dept> getAllDeptList()
	{
		List<Dept> sortDeptList = new ArrayList<Dept>();
		List<Dept> deptList =  deptService.getDeptList();
		TreeUtil.sortTreeList(deptList, sortDeptList, 0);
		Dept tmpDept = new Dept();
		tmpDept.setName("");
		sortDeptList.add(tmpDept);
		return sortDeptList;
	}
	
}
